package com.shop.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * @author wenjuanhenxing
 * @version V1.0 VerifyCode.java 2016-2-12 下午11:49:26
 */
public class VerifyCode {
	public static void getVerifyCode(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// 指定生成验证码的宽度和高度
		int width = 86, height = 22;
		int fontHeight = 18;
		// 定义图片上显示验证码的个数
		int codeCount = 4;
		int xx = 15;
		int codeY = 16;
		BufferedImage buffImg = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D gd = (Graphics2D) buffImg.getGraphics();
		// 将图像填充为白色
		gd.setColor(Color.WHITE);
		// 绘制背景
		gd.fillRect(0, 0, width, height);
		// 创建字体，字体的大小应该根据图片的高度来定
		Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
		// 设置字体
		gd.setFont(font);
		// 画边框
		gd.setColor(Color.BLACK);
		gd.drawRect(0, 0, width - 1, height - 1);
		// 创建一个随机数生成器类
		Random random = new Random();
		// 随机产生20条干扰线，使图象中的认证码不易被其它程序探测到
		gd.setColor(Color.BLACK);
		for (int i = 0; i < 20; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xlen = random.nextInt(12);
			int ylen = random.nextInt(12);
			gd.drawLine(x, y, x + xlen, y + ylen);
		}

		// randomCode 保存随机产生的验证码
		StringBuffer randomCode = new StringBuffer();
		int red = 0, green = 0, blue = 0;
		// 随机产生codeCount数字的验证码
		for (int i = 0; i < codeCount; i++) {
			int kind = random.nextInt(3);
			char ch = '0';
			switch (kind) {
			case 0: // 生成A-Z
				ch = (char) (random.nextInt(26) + 'A');
				break;
			case 1:
				ch = (char) (random.nextInt(26) + 'a');
				break;
			default:
				ch = (char) (random.nextInt(10) + '0');
				break;
			}
			// 得到随机产生的字符
			String code = String.valueOf(ch);
			// 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同
			red = random.nextInt(255);
			green = random.nextInt(255);
			blue = random.nextInt(255);

			// 用随机产生的颜色将验证码绘制到图像中
			gd.setColor(new Color(red, green, blue));
			gd.drawString(code, (i + 1) * xx, codeY);

			// 将产生的四个随机数组合在一起
			randomCode.append(code);
		}
		// 将四位数字的验证码保存到Session中
		HttpSession session = request.getSession();
		System.out.println(randomCode);
		session.setAttribute("randcode", randomCode.toString());
		// 设置不缓存图片
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 图像输出到Servlet输出流中
		ImageIO.write(buffImg, "JPEG", response.getOutputStream());
		// 释放g所占用的系统资源
		gd.dispose();
	}
}
